/**
 * JAVACC DEMO 1.0
 * @copy right dwusoft company All rights reserved. 
 * @Package com.apache.uct.controller  
 */
package com.apache.uct.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.apache.api.manager.BaseManager;
import com.apache.api.manager.ProxyManager;
import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultMsg;
import com.apache.api.vo.Token;
import com.apache.database.constant.Validator;
import com.apache.database.model.Page;
import com.apache.tools.DateUtils;
import com.apache.tools.StrUtil;
import com.apache.tools.TreeNode;
import com.apache.uct.common.BaseAction;
import com.apache.uct.common.entity.Act;
import com.apache.uct.common.entity.User;
import com.apache.uct.manager.ActManager;
import com.apache.uct.manager.UserManager;

/**
 * description:  权限管理action
 * @author dwusoft 创建时间：2015-3-25  
 * @Copyright(c)2014:北京--软件技术有限公司
 */
@Controller
@RequestMapping("uct/act/")
public class ActAction extends BaseAction<Act> {

	@Autowired
	private ActManager actManager;
	@Autowired
	private ProxyManager uctProxyManager;
	@Autowired
	private UserManager userManager;

	//获取权限列表
	@RequestMapping("act!data.action")
	@ResponseBody
	protected Object data(HttpServletRequest request, String page, String rows) {
		String id = Validator.getDefaultStr(request.getParameter("id"), "0");
		ParamsVo<Act> pvo = new ParamsVo<Act>();
		Act act = new Act();
		act.setFatherId(id);
		pvo.setObj(act);
		List<Act> actList = actManager.getList(pvo);
		net.sf.json.JSONArray jary = new net.sf.json.JSONArray();
		if (Validator.isEmpty(actList))
			return jary;
		for (int i = 0; i < actList.size(); i++) {
			Act vo = actList.get(i);
			net.sf.json.JSONObject jvo = net.sf.json.JSONObject.fromObject(vo);
			if (vo.getSubCount() != null && vo.getSubCount() > 0) {
				jvo.put("state", "closed");
			} else {
				jvo.put("state", "opened");
			}
			jary.add(jvo);
		}
		return jary;
	}

	//获取权限树
	@RequestMapping("act!actTree.action")
	@ResponseBody
	protected Object actTree(HttpServletRequest request) {
		net.sf.json.JSONArray jary = new net.sf.json.JSONArray();
		String id = Validator.getDefaultStr(request.getParameter("id"), "0");
		String sysEname = Validator.getDefaultStr(request.getParameter("sysEname"), "");
		ParamsVo<Act> pvo = new ParamsVo<Act>();
		Act act = new Act();
		act.setFatherId(id);
		act.setSysEname(sysEname);
		pvo.setObj(act);
		List<Act> actList = actManager.getList(pvo);
		if (Validator.isEmpty(actList))
			return jary;
		String fullEname = "";
		String actId = request.getParameter("actId");
		if ("0".equals(id) && Validator.isNotNull(actId)) {
			pvo = new ParamsVo<Act>();
			pvo.setInfoId(actId);
			Act avo = (Act) actManager.getInfoById(pvo);
			if (null != avo) {
				fullEname = avo.getFullEname();
			}
		}
		for (int i = 0; i < actList.size(); i++) {
			Act vo = actList.get(i);
			TreeNode tvo = toTreeVo(vo);
			if (StrUtil.isNotNull(fullEname)) {
				//如果当前id在默认选中值的家族中，则构造树，并展开
				if (fullEname.startsWith(vo.getFullEname())) {
					tvo = getSubTree(tvo, vo, fullEname);
					tvo.setState("opened");
				}
			}
			jary.add(tvo);
		}
		return jary;
	}

	/**
	 * 功能说明：通用跳转到新增页面
	 */
	@Token(save = true)
	@RequestMapping(value = "add.action", method = RequestMethod.GET)
	protected ModelAndView add(HttpServletRequest request) {
		ModelAndView view = new ModelAndView(ADD);
		Act act = new Act();
		if (Validator.isNotNull(request.getParameter("id"))) {
			ParamsVo<Act> vo = new ParamsVo<Act>();
			vo.setInfoId(request.getParameter("id"));
			act = (Act) actManager.getInfoById(vo);
		} else {
			act.setFatherId(Validator.getDefaultStr(request.getParameter("fatherId"), "0"));
			act.setActStatus(1);
			act.setActType("menu");
		}
		view.addObject("item", act);
		return view;
	}

	@Token(remove = true)
	@RequestMapping(value = "/save.action", method = RequestMethod.POST)
	@ResponseBody
	public ResultMsg save(HttpServletRequest request, HttpServletResponse response, @ModelAttribute Act item) {
		ResultMsg rmsg = new ResultMsg("T", "操作成功！");
		ParamsVo<Act> vo = getParamsVo(request);
		long times = DateUtils.toLong(new Date());
		User user = this.getSessionUser(request);
		if (Validator.isNotNull(item.getActId())) {//对权限信息修改
			item.setUpdateTime(times);
			item.setUpdateUser(user.getUserEname());
			buildAct(item);
			vo.setObj(item);
			boolean mark = getBaseManager().editInfo(vo);
			if (!mark) {
				rmsg = getResultMsg(request, "信息修改失败！");
			}
		} else {//添加角色信息
			item.setCreateUser(user.getUserEname());
			item.setUpdateCount(0);
			item.setCreateTime(times);
			item.setCreateUser(user.getUserEname());
			buildAct(item);
			vo.setObj(item);
			vo.setKey("checkActEname");
			String flag = String.valueOf(actManager.execute(vo));
			if ("true".equals(flag)) {
				String id = getBaseManager().saveInfo(vo);
				if (Validator.isNull(id)) {
					rmsg = getResultMsg(request, "信息添加失败！");
				}
			} else {
				rmsg = getResultMsg(request, "权限标识已存在,操作失败！");
			}
		}
		return rmsg;
	}

	/**
	 * 组织权限数据
	 */
	private void buildAct(Act item) {
		if (Validator.isNull(item.getFullEname())) {
			if (!"0".equals(item.getFatherId())) {
				ParamsVo<Act> pvo = new ParamsVo<Act>();
				pvo.setInfoId(item.getFatherId());
				Act act = (Act) actManager.getInfoById(pvo);
				item.setFullEname(Validator.getDefaultStr(act.getFullEname(), act.getActEname()) + "/"
						+ item.getActEname());
				item.setFullCname(act.getActCname() + "/" + item.getActCname());
				item.setSysEname(act.getSysEname());
			} else {
				item.setFullEname("/" + item.getActEname());
				item.setFullCname("/" + item.getActCname());
			}
		}
	}

	//删除机构信息
	@RequestMapping("del.action")
	@ResponseBody
	public ResultMsg delete(HttpServletRequest request, String id) {
		ResultMsg rmsg = new ResultMsg("T", "删除成功！");
		ParamsVo<Act> vo = getParamsVo(request);
		if (isNotNull(id)) {
			vo.setInfoId(id);
			vo.setKey("deleteOrg");
			vo.setParams("infoType", "act");
			String msg = String.valueOf(uctProxyManager.doInvoke(vo));
			if (Validator.isNotNull(msg)) {
				rmsg.setFlag("F");
				rmsg.setMsg(msg);
			}
		} else {
			rmsg.setFlag("H");
			rmsg.setMsg("请选择要删除的角色！");
		}
		return rmsg;
	}

	@RequestMapping("act-user-list!data.action")
	@ResponseBody
	protected Object actUserList(HttpServletRequest request, String page, String rows) {
		ParamsVo<User> vo = new ParamsVo<User>();
		if (Validator.isNotNull(request.getParameter("actId"))) {
			vo.setParams("actId", request.getParameter("actId"));
		}
		if (Validator.isNotNull(request.getParameter("userEname"))) {
			vo.setParams("userEname", request.getParameter("userEname"));
		}
		if (Validator.isNotNull(request.getParameter("userCname"))) {
			vo.setParams("userCname", request.getParameter("userCname"));
		}
		vo.setParams("pageIndex", page);
		vo.setParams("pageSize", rows);
		vo.setKey("userList");
		Page pageList = (Page) userManager.execute(vo);
		Map<String, Object> mapData = new HashMap<String, Object>();
		mapData.put("total", pageList.getCount());
		mapData.put("rows", pageList.getPageObjects());
		return mapData;
	}

	/**
	 * 功能说明：跳转到持有某权限值用户列表页面
	 */
	@RequestMapping(value = "act-user-list.action", method = RequestMethod.GET)
	protected ModelAndView actUserList(HttpServletRequest request) {
		ModelAndView view = new ModelAndView(getPrefix() + "user-list");
		view.addObject("actId", request.getParameter("actId"));
		return view;
	}

	protected BaseManager<Act> getBaseManager() {
		return actManager;
	}

	protected String getPrefix() {
		return "uct/act-";
	}

	/**
	 * 将Act转成程TreeNode
	 * @param vo
	 * @return TreeNode
	 */
	private TreeNode toTreeVo(Act vo) {
		TreeNode tvo = new TreeNode();
		tvo.setChecked("checked");
		tvo.setIconCls("");
		if (vo.getSubCount() > 0) {
			tvo.setState("closed");
		} else {
			tvo.setState("opened");
		}
		tvo.setId(vo.getActId());
		tvo.setText(vo.getActCname());
		return tvo;
	}

	/**
	 * 递归查询所有子节点
	 * @param treeNode
	 * @param act
	 * @param fullEname
	 * @return TreeNode
	 */
	private TreeNode getSubTree(TreeNode treeNode, Act act, String fullEname) {
		ParamsVo<Act> pvo = new ParamsVo<Act>();
		Act actvo = new Act();
		actvo.setFatherId(act.getActId());
		pvo.setObj(actvo);
		List<Act> list = actManager.getList(pvo);
		List<TreeNode> children = new ArrayList<TreeNode>();
		if (list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				Act vo = list.get(i);
				TreeNode tvo = toTreeVo(vo);
				if (fullEname.startsWith(vo.getFullEname())) {
					tvo.setState("opened");
				}
				children.add(getSubTree(tvo, vo, fullEname));
			}
		}
		treeNode.setChildren(children);
		return treeNode;
	}
}
